#!/bin/bash

##
##	file: ledaps-machine.sh
##
##	purpose: get landsat scenes form san and process with ledaps and fmask
##
##	coder: moenkemt@geo.hu-berlin.de
##

function do_ledaps() {
	export ANC_PATH='/opt/ledaps/LedapsAnc'
	export ESUN='/opt/cfmask/src/'
	export LEDAPS_BIN='/usr/bin'
	meta_file=$1
	echo "Processing metafile $meta_file..."
	meta=`echo $meta_file | sed -e 's/.txt//' -e 's/_MTL//' -e 's/.met//'`
	touch .lock
	lndpm $meta_file
	lndcal lndcal.$meta.txt
#	lndcsm lndcsm.$meta.txt
	lndsr lndsr.$meta.txt
	lndsrbm.ksh lndsr.$meta.txt
#	/opt/fmask/run_Fmask.sh /usr/local/MATLAB/MATLAB_Compiler_Runtime/v81 3 3 3 1
	for toarefl in $(ls lndcal.*.hdf); do
		cfmask  --toarefl=$toarefl --prob=1.0 --cldpix=3 --sdpix=3 --write_binary --no_hdf_out
	done
	rm .lock README.GTF LogReport
}

function do_all_archives() {
	cd /home/ledaps
	for landsat in $(ls L*.tar.gz); do
		echo "Processing scene $landsat..."
		landsatdir=`basename $landsat .tar.gz`
		# untar if not exist
		if [ ! -d $landsatdir ]; then
	    		echo "Creating scene $landsatdir..."
			mkdir $landsatdir
			cd $landsatdir
			tar -xvzf ../$landsat
			cd ..
		fi

		mtlext="_MTL.txt"
		cd $landsatdir
		mtlfile=$landsatdir$mtlext;
		# start ledaps in background, only if not locked
		if [ ! -f .lock ]; then
			do_ledaps $mtlfile &
		fi
		cd ..
	done
}

function get_some_files() {
	umount /san
	mount -t cifs -o vers=3.0,username=debian,password=linux,uid=0,gid=100,file_mode=0660,dir_mode=0770 //141.20.140.91/SAN_RSD1Brazil /san
	cd /home/ledaps
	for landsat in $(ls -tr /san/LandsatData/incoming/L*.tar.gz | head -n $1); do
		echo Getting file $landsat...
		mv $landsat .
	done
}

function store_files() {
	cd /home/ledaps
	for landsat in $(ls L*.tar.gz); do
		echo "Storing scene $landsat..."
		landsatdir=`basename $landsat .tar.gz`
		donefile=$landsatdir/lndsr.$landsatdir.hdf.hdr
		ls_path=`echo $landsatdir | cut -c 4-6`
		ls_row=`echo $landsatdir | cut -c 7-9`
		ls_target=/san/LandsatData/outgoing/$ls_path"_"$ls_row		
		if [ ! -f $landsatdir/.lock ]; then
			rm $landsatdir/*.TIF
			if [ ! -d $ls_target ]; then
				echo Creating $ls_target...
				mkdir $ls_target
			fi
			echo Moving to $ls_target...
			mv $landsatdir $ls_target
			rm $landsat			
		fi		
	done
}


# main (nearly infinite loop)
for ((i=1; i<=5000; i++)); do
	store_files
	numfiles=`ls -tr /home/ledaps/L*.tar.gz | wc -l`
	echo $numfiles "files in process..."
	if [ "$numfiles" -lt "4" ]
	then
		echo "Start..."
		get_some_files 8
		do_all_archives
	fi
	echo "Idle..."
	sleep 180
done
